package org.example.bumenguanli.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.example.bumenguanli.exception.CannotDeleteClassException;
import org.example.bumenguanli.mapper.ClazzMapper;
import org.example.bumenguanli.pojo.*;
import org.example.bumenguanli.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;

    @Override
    public PageResult page(EmpQueryParam empQueryParam) {
        //1. 设置PageHelper分页参数
        PageHelper.startPage(empQueryParam.getPage(), empQueryParam.getPageSize());
        //2. 执行查询
        // 获取当前的日期和时间
        LocalDateTime currentDateTime = LocalDateTime.now();
        // 将 LocalDateTime 转换为 LocalDate
        LocalDate currentDate = currentDateTime.toLocalDate();
        List<Clazz> empList = clazzMapper.list(empQueryParam);
        for (Clazz clazz : empList) {
            if(currentDate.isAfter(clazz.getEndDate())){
                clazz.setStatus("已结课");
            }else if(currentDate.isBefore(clazz.getBeginDate())){
                clazz.setStatus("未开课");
            }else {
                clazz.setStatus("在读中");
            }
        }

       /* Integer empId = emp.getId();
        List<EmpExpr> exprList = emp.getExprList();
        if(!CollectionUtils.isEmpty(exprList)){
            exprList.forEach(empExpr -> empExpr.setEmpId(empId));
            empExprMapper.insertBatch(exprList);
        }*/
        //3. 封装分页结果
        Page<Clazz> p = (Page<Clazz>)empList;
        return new PageResult(p.getTotal(), p.getResult());
    }

    @Override
    public void save(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazz.setCreateTime(LocalDateTime.now());
        clazzMapper.save(clazz);
    }

    @Override
    public Clazz getInfo(Integer id) {
        return clazzMapper.getinfo(id);
    }

    @Override
    public void update(Clazz clazz) {
        clazzMapper.update(clazz);
    }

    @Override
    @Transactional
    public void delete(Integer id) {
        Student student = clazzMapper.getStudent(id);
        if (student!=null){
            throw new CannotDeleteClassException("该班级有学生，不能删除");
        }
        clazzMapper.delete(id);

    }

    @Override
    public List<Clazz> clazzlist(Clazz clazz) {
        return clazzMapper.clazzlist(clazz);
    }
}
